package com.clouddisk.file.chain.impl;

import com.clouddisk.common.exception.BusinessException;
import com.clouddisk.file.chain.FileOperationHandler;
import com.clouddisk.file.chain.FileOperationContext;
import com.clouddisk.file.factory.FileHandlerFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.io.IOException;

@Component
@RequiredArgsConstructor
public class FileUploadHandler implements FileOperationHandler {

    private final FileHandlerFactory fileHandlerFactory;
    private FileOperationHandler next;

    @Override
    public void handle(FileOperationContext context) {
        if (!context.isShouldContinue()) {
            return;
        }

        try {
            // 计算文件MD5
            String fileMd5 = DigestUtils.md5DigestAsHex(context.getUploadDTO().getFile().getInputStream());
            context.setFileMd5(fileMd5);

            // 获取对应的文件处理器
            String storagePath = fileHandlerFactory.getHandler(context.getUploadDTO().getFile())
                    .handleUpload(context.getUploadDTO().getFile());
            context.setStoragePath(storagePath);

            if (next != null) {
                next.handle(context);
            }
        } catch (IOException e) {
            throw new BusinessException("文件上传失败");
        }
    }

    @Override
    public void setNext(FileOperationHandler next) {
        this.next = next;
    }
} 